package com.handong.handserialprogram.module.singletask;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.handong.handserialprogram.R;
import com.handong.handserialprogram.constants.ColorContant;
import com.handong.handserialprogram.constants.KeyConstant;
import com.handong.handserialprogram.model.entities.CriminalEntity;
import com.handong.handserialprogram.model.entities.FootRingNewEntity;
import com.handong.handserialprogram.model.status.FootRingStatus;
import com.handong.handserialprogram.module.setring.SetRingActivity;
import com.handong.handserialprogram.module.singleperson.SinglePersonActivity;
import com.handong.handserialprogram.utils.AppUtil;

import java.util.ArrayList;
import java.util.List;

import cn.pda.serialport.SerialPort;

/**
 * 罪犯列表
 */
public class CriminalListAdapter extends RecyclerView.Adapter<CriminalListAdapter.ViewHolder> {

    private Context mContext;
    private MissionActivity mActivity;
    private List<CriminalEntity> mPersonEntityList;
    private View mFirstView = null;
    private int mIndex = -1;
    private Thread myThread ;
    public CriminalListAdapter(List<CriminalEntity> list, MissionActivity activity) {
        mPersonEntityList = list;
        mActivity = activity;
        mContext = activity.getApplicationContext();
    }

    @Override
    public CriminalListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.adapter_person_list, parent, false);
        return new CriminalListAdapter.ViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(CriminalListAdapter.ViewHolder holder, int position) {
        CriminalEntity entity = mPersonEntityList.get(position);
        //存放实例。
        holder.mEntity = entity;
        //存放坐标。
        holder.personName.setTag(position);
        if (entity.getPersonId()!=null&&!entity.getPersonId().trim().equals("")) {

            holder.personName.setText(entity.getPName());
            holder.personID.setText("编号: " + entity.getPersonId());
        }else{
            holder.personName.setText("");
            holder.personID.setText(entity.getEquipmentId());
        }

        //分类处理，是否已绑定脚环。
        FootRingNewEntity ringEntity = entity.getRingEntity();


            if (null == ringEntity) {
                if (entity.getEquipmentId()!=null&&!entity.getEquipmentId().equals(""))
                {
                    if (holder.alreadySetLayout.getVisibility() == View.GONE) {
                        holder.alreadySetLayout.setVisibility(View.VISIBLE);
                        holder.setRingLayout.setVisibility(View.GONE);
                        holder.personStatus.setVisibility(View.VISIBLE);
                    }
                    GradientDrawable drawable = (GradientDrawable) holder.personStatus.getBackground();
                    holder.personStatus.setText(R.string.ring_status_escape);
                    drawable.setColor(ColorContant.PERSON_ESCAPE);
                    holder.personActualDistance.setText("0m");
                }
                else {
                    if (holder.setRingLayout.getVisibility() == View.GONE) {
                        holder.setRingLayout.setVisibility(View.VISIBLE);
                        holder.alreadySetLayout.setVisibility(View.GONE);

                        if ((position == 0) && mFirstView == null) {
                            mFirstView = holder.btnPersonSetRing;
                        }
                    }
                    if (holder.personStatus.getVisibility() == View.VISIBLE) {
                        holder.personStatus.setVisibility(View.GONE);
                    }
                }

            } else {
                if (holder.alreadySetLayout.getVisibility() == View.GONE) {
                    holder.alreadySetLayout.setVisibility(View.VISIBLE);
                    holder.setRingLayout.setVisibility(View.GONE);
                    holder.personStatus.setVisibility(View.VISIBLE);
                }
                //if (ringEntity)
                final int status=ringEntity.getStatus();
                GradientDrawable drawable = (GradientDrawable) holder.personStatus.getBackground();
                if (status == FootRingStatus.ESCAPE) {
                    holder.personStatus.setText(R.string.ring_status_escape);
                    drawable.setColor(ColorContant.PERSON_ESCAPE);
                     if (myThread ==null){
                         myThread=new Thread(new MyRunnable());
                         myThread.start();
                     }


                }else if(status == FootRingStatus.NODATA){
                    holder.personStatus.setText(R.string.ring_status_nodata);
                    drawable.setColor(Color.parseColor("#C0C0C0"));
                }
                else {
                    if (status == FootRingStatus.NORMAL && ringEntity.getActualRingDistance() < ringEntity.getSetRingDistance()) {
                        holder.personStatus.setText(R.string.ring_status_normal);
                        drawable.setColor(ColorContant.PERSON_NORMAL);
                    } else {
                        //holder.personStatus.setText(R.string.ring_status_exception);
                        if (status==FootRingStatus.NORMAL)
                        {
                            holder.personStatus.setText(R.string.ring_status_exception);
                        }
                        else{
                            holder.personStatus.setText(R.string.ring_status_week);
                        }
                        drawable.setColor(ColorContant.PERSON_EXCEPTION);
                    }
                }
                holder.personActualDistance.setText(ringEntity.getActualRingDistance() + "m");

        }
    }

    public View getFirstView() {
        return mFirstView;
    }

    public void resetIndex() {
        mIndex = -1;
    }

    public void addFootRing(FootRingNewEntity entity) {
        mPersonEntityList.get(mIndex).setRingEntity(entity);
        notifyItemChanged(mIndex);
        //notifyDataSetChanged();
        mIndex = -1;
    }

    @Override
    public int getItemCount() {
        return mPersonEntityList == null ? 0 : mPersonEntityList.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        private CriminalEntity mEntity;

        private TextView personName, personStatus, personID, btnPersonSetRing, personActualDistance;

        private RelativeLayout setRingLayout;
        private LinearLayout alreadySetLayout;

        public ViewHolder(View itemView) {
            super(itemView);
            personName = (TextView) itemView.findViewById(R.id.personName);
            personID = (TextView) itemView.findViewById(R.id.personID);
            personStatus = (TextView) itemView.findViewById(R.id.personStatus);
            btnPersonSetRing = (TextView) itemView.findViewById(R.id.btnPersonSetRing);
            personActualDistance = (TextView) itemView.findViewById(R.id.personActualDistance);
            setRingLayout = (RelativeLayout) itemView.findViewById(R.id.ringSettingLayout);
            alreadySetLayout = (LinearLayout) itemView.findViewById(R.id.alreadySetLayout);
            itemView.setOnClickListener(this);
            setRingLayout.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {

            switch (v.getId()) {
                case R.id.ringSettingLayout://设置脚环
                    // todo 改为一对一
                    boolean flag=true;
                    for (CriminalEntity criminalEntity:mPersonEntityList) {
                        if(criminalEntity.getRingEntity()==null){
                            flag=false;
                        }
                    }
                    if (flag) {
                        AppUtil.showShortToast(mActivity, "脚环已经绑定");
                        return;
                    }




                    int index = (int) personName.getTag();
                    mIndex = index;

                    Bundle bundle = new Bundle();
                    ArrayList<CriminalEntity> criminalEntities=new ArrayList<CriminalEntity>();
                    criminalEntities.addAll(mPersonEntityList);
                    bundle.putSerializable(KeyConstant.CRIMINALS_LIST,criminalEntities);
                    bundle.putParcelable(KeyConstant.SINGLE_PERSON, mEntity);
                    mActivity.openActWithAnim(SetRingActivity.class, bundle, index, KeyConstant.INDEX_0);
                    break;

                default://设置脚环成功后进入犯人详情
                    if (mEntity.getRingEntity() != null) {
                        Bundle bundle2 = new Bundle();
                        //int index2 = (int) personName.getTag();
                       // bundle2.putInt(KeyConstant.POSITION, index2);
                        bundle2.putString(KeyConstant.PERSON_NAME, mEntity.getPName()!=null?mEntity.getPName() + " - " + mEntity.getRingEntity().getRingID():mEntity.getRingEntity().getRingID());
                        bundle2.putFloat(KeyConstant.PERSON_DISTANCE, mEntity.getRingEntity().getActualRingDistance());
                        bundle2.putInt(KeyConstant.PERSON_SET_DISTANCE, mEntity.getRingEntity().getSetRingDistance());
                        bundle2.putString(KeyConstant.PERSON_RING_ID, mEntity.getRingEntity().getRingID());
                        bundle2.putBoolean(KeyConstant.EMPOWER_STATE,mEntity.getRingEntity().isEmpower());
                        bundle2.putBoolean(KeyConstant.WITHDRAW_STATE,mEntity.getRingEntity().isWithdraw());
                        bundle2.putBoolean(KeyConstant.WARNNING_STATE,mEntity.getRingEntity().isStopAlarm());

                        bundle2.putInt(KeyConstant.RING_STATUS,mEntity.getRingEntity().getStatus());
                        bundle2.putInt(KeyConstant.LINE_STATUS,mEntity.getRingEntity().getBrokenType());
                        bundle2.putInt(KeyConstant.LOCK_STATUS,mEntity.getRingEntity().getLockType());
                        bundle2.putInt(KeyConstant.ELECTRIC_STATUS,mEntity.getRingEntity().getTruePower());
                        bundle2.putString(KeyConstant.FOOT_VERSION,mEntity.getRingEntity().getVersion());
                        mActivity.openActivity(SinglePersonActivity.class, bundle2);
                    } else {
                        mActivity.showGuideView(btnPersonSetRing, R.id.btnPersonSetRing);
                    }
                    break;
            }
        }
    }

    private static class MyRunnable implements Runnable {
        @Override
        public void run() {
            SerialPort mSerialPort = new SerialPort();
            try {
                Log.d("zzz", "线程开始等待10s");
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Log.d("zzz", "准备关闭rfid");

            mSerialPort.rfid_poweroff();
            try {
                Log.d("zzz", "线程开始等待3s");
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Log.d("zzz", "准备开启rfid");
            mSerialPort.rfid_poweron();
        }
    }

}

